<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>jsonp</title>
</head>
<body>
    
    <script>

        // 通过在页面上创建一个 script标签 来代理发送 请求；
        const jsonp = (({url,params,callback}) => {

            const cancatURL = (url,params,callback) => {

                let dataStr = '';
                for(let key in params) {
                    dataStr += `${key}=${params[key]}&`;

                }
                const callbackStr = `callback=${callback}`
                return url + '?' + dataStr + callbackStr;

            }

            return new Promise( (resolve,reject) => {

                let callbackName = callback || 'cb' + Math.random().toString().replace('.','') ;

                // 创建一个 script 标签
                let script = document.createElement('script');
                script.src =  cancatURL(url,params,callback);

                document.body.append(script);
                window[callback] = function(data) {
                    
                    console.log(data);
                    resolve(data);
                    document.body.remove(script);

                }
            })
        })

        jsonp({
            url:'http://localhost:3000',
            params:{
                name:"格格",
                age:18
            },
            callback:'getData'
        })
        .then( data => data)
        .then(data => {
            // console.log(data);
        })
    </script>
</body>
</html>